package cn.gzsf.csmall.product.service.impl;


import cn.gzsf.csmall.product.cache.IAlbumCacheRepository;
import cn.gzsf.csmall.product.ex.ServiceException;
import cn.gzsf.csmall.product.mapper.AlbumMapper;
import cn.gzsf.csmall.product.mapper.PictureMapper;
import cn.gzsf.csmall.product.pojo.entity.Album;
import cn.gzsf.csmall.product.pojo.entity.Picture;
import cn.gzsf.csmall.product.pojo.param.AlbumAddNewParam;
import cn.gzsf.csmall.product.pojo.param.AlbumUpdateInfoParam;
import cn.gzsf.csmall.product.pojo.vo.AlbumListItemVO;
import cn.gzsf.csmall.product.pojo.vo.AlbumStandardVO;
import cn.gzsf.csmall.product.pojo.vo.PageData;
import cn.gzsf.csmall.product.service.IAlbumService;
import cn.gzsf.csmall.product.util.PageInfoToPageDataConverter;
import cn.gzsf.csmall.product.web.ServiceCode;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service   //Service层必须@Service注解
public class AlbumServiceImpl implements IAlbumService {

    @Autowired
    private AlbumMapper albumMapper;

    @Autowired
    private PictureMapper pictureMapper;

    @Autowired
    private IAlbumCacheRepository albumCacheRepository;

    @Override
    public void addNew(AlbumAddNewParam albumAddNewParam)  {
        log.debug("开始处理[添加相册]的业务，参数：" + albumAddNewParam);
        //"".substring(1000);
        //检查相册名称是否被占用，如果被占用，则抛出异常
        QueryWrapper<Album> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",albumAddNewParam.getName());
        int countByname = albumMapper.selectCount(queryWrapper);
        log.debug("根据相册名统计匹配的相册数量：结果：{},{}",countByname);
        if(countByname>0){
            String message = "添加相册失败，相册名称被占用";
            log.warn(message);
            throw new ServiceException(message);
        }
        //将相册数据写入数据库中
        Album album = new Album();
        BeanUtils.copyProperties(albumAddNewParam,album);
        album.setGmtCreate(LocalDateTime.now());
        album.setGmtModified(LocalDateTime.now());
        log.debug("准备将新相册的数据插入数据库，数据：{}", album);
        albumMapper.insert(album);
        log.debug("将新相册的数据插入数据库完成！");
    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理【删除相册】的业务，参数：{}",id);
        //检查相册是否存在，如果不存在，则抛出异常
        QueryWrapper<Album> queryWrapper =  new QueryWrapper<>();
        queryWrapper.eq("id",id);//where id=1
        int countById = albumMapper.selectCount(queryWrapper);
        log.debug("根据ID统计匹配的相册数量，结果:{}",countById);
        if(countById==0){
            String message = "删除相册失败，相册数据不存在!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        //检查是否有图片关联此相册，如果存在，则抛出异常
        QueryWrapper<Picture> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("album_id",id);
        int countByAlbumId = pictureMapper.selectCount(queryWrapper2);
        if(countByAlbumId>0){
            String message = "删除相册失败,仍有图片关联此相册";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
        //检查是否有SPU、SKU关联此相册，如果存在，则抛出异常


        albumMapper.deleteById(id);
    }

    @Override
    public void updateInfoById(Long id, AlbumUpdateInfoParam albumUpdateInfoParam) {
        log.debug("开始处理【修改相册详情】的业务，id:{},参数:{}",id,albumUpdateInfoParam);
        //检查相册是否存在，如果不存在，则抛出异常
        QueryWrapper<Album> queryWrapper =  new QueryWrapper<>();
        queryWrapper.eq("id",id);//where id=1
        int countById = albumMapper.selectCount(queryWrapper);
        log.debug("根据ID统计匹配的相册数量，结果:{}",countById);
        if(countById==0){
            String message = "修改相册失败，相册数据不存在!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        //检查相册名称是否被其他相册占用，如果被占用，则抛出异常
        QueryWrapper<Album> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("name",albumUpdateInfoParam.getName())//name=xx
                .ne("id",id);//id<>xx  除了自身以外，是否存在同名的相册   where name=xxx and id<>xxx
        int countByname = albumMapper.selectCount(queryWrapper2);
        log.debug("根据相册名统计匹配的相册数量：结果：{},{}",countByname);
        if(countByname>0){
            String message = "添加相册失败，相册名称被占用";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        Album album = new Album();
        BeanUtils.copyProperties(albumUpdateInfoParam,album);
        album.setId(id);
        albumMapper.updateById(album);
        log.debug("将新的相册数据更新到数据库，完成!");
    }

    @Override
    public AlbumStandardVO getStandardVO(Long id) {
        log.debug("开始处理【根据ID查询相册详情】,参数：{}",id);
        //先去redis取数据
        AlbumStandardVO albumStandardVO = albumCacheRepository.getStandardById(id);
        if(albumStandardVO==null){//说明redis里面没有数据
            AlbumStandardVO standard = albumMapper.getStandard(id);//从数据库中查
            if(standard==null){//数据库中也没数据，则抛出异常
                String message = "查询相册详情失败，相册数据不存在!";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
            }
            albumCacheRepository.setStandard(albumStandardVO);
            return standard;//从数据库中查到数据，返回数据
        }
        return albumStandardVO;//从redis中查到数据，返回
    }

    @Override
    public PageData<AlbumListItemVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理【查询相册列表】的页面，页码:{},每页记录数:{}",pageNum,pageSize);
        PageHelper.startPage(pageNum,pageSize);
        List<AlbumListItemVO> list = albumMapper.list();
        PageInfo<AlbumListItemVO> pageInfo = new PageInfo<>(list);
        PageData<AlbumListItemVO> pageData = PageInfoToPageDataConverter.convert(pageInfo);
        log.debug("查询完成，即将返回：{}",pageData);
        return pageData;
    }
    @Override
    public PageData<AlbumListItemVO> list(Integer pageNum) {
        Integer pageSize = 5;
        return list(pageNum,pageSize);
    }
}
